/****************************************
 * 2018 - 2021 版权所有 CopyRight(c) 快程乐码信息科技有限公司所有, 未经授权，不得复制、转发
 */

package com.kclm.security.demo.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;

/******************
 * @Author yejf
 * @Version v1.0
 * @Create 2020-07-20 10:53
 * @Description TODO
 */
@Slf4j
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    /***************
     * 认证成功后的处理方法，重写 onAuthenticationSuccess方法， 获取当前用户的权限，根据权限跳转到指定的URL路径
     * @param httpServletRequest
     * @param httpServletResponse
     * @param authentication
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                        Authentication authentication) throws IOException, ServletException {
        log.debug("认证成功后进入 onAuthenticationSuccess方法 ....");
        //获取当前用户的权限
        //authentication.getAuthorities();
        final Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
        //
        log.debug("当前认证的用户拥有角色数："+roles.size());
        for(String role : roles) {
            log.debug(role);
        }
        //获取登录者的权限，然后做跳转
        if(roles.contains("ROLE_ADMIN")) {
            log.debug("拥有ADMIN角色，跳转到 /admin 资源");
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/admin");
            return;
        } else if(roles.contains("ROLE_USER")) {
            log.debug("拥有 USER 角色，跳转到 /home 资源");
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/home");
            return ;
        } else {
            log.warn("无任何角色，进入提示无权限访问的页面");
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/accessDenied");
        }
    }

}
